import React, { useEffect, useRef, useState } from "react";
import styles from "./index.module.scss";
import {
  CalendarOutline,
  StarOutline,
  CheckCircleOutline,
  CloseCircleOutline,
} from "antd-mobile-icons";
import {
  Button,
  Checkbox,
  Radio,
  Space,
  Swiper,
  Tag,
  TextArea,
  Toast,
} from "antd-mobile";
import { useNavigate, useSearchParams } from "react-router-dom";
import { ApiQdTest, ApiQdTestPut } from "@/utils/api";
type Props = {};

export default function index({}: Props) {
  const navigate = useNavigate(); // 跳转
  const [searchParams, setSearchParams] = useSearchParams(); //获取路径上携带的参数
  const [testData, setTestData] = useState<Array<IData>>(); //响应数据
  // 题目列表数据请求
  const getData = async () => {
    let actionCode = searchParams.get("actionCode"); //唯一编码
    let testNum = searchParams.get("testNum"); //数量
    let testType = searchParams.get("testType"); //类型
    let questionType = searchParams.get("questionType"); //科目
    let res = await ApiQdTest({
      testNum, //数量
      testType, //all 全部,err 错误,done 已做,notdone 没做
      actionCode, //练习题列表 接口上面那个 actionCode
      questionType, //all 全部 qa 问答, fill 填空 , one 单选,check 判断 ,code 编程 ,many 多选
    });
    if (res.errCode !== 0) {
      Toast.show({
        icon: "fail",
        content: res.message,
      });
      return;
    }
    setTestData(res.data); //修改响应数据
  };

  const questionTypeData = useRef<any>({
    //全局变量
    all: "全部",
    qa: "问答",
    fill: "填空",
    code: "编程",
    one: "单选",
    check: "判断",
    many: "多选",
  }); //类型数据

  //确认
  const confirm = async (item: IData) => {
    if (!item.userAnswer) {
      Toast.show({
        icon: "fail",
        content: "内容不能为空！",
      });
      return;
    }
    let res = await ApiQdTestPut({
      categoryCode: item.categoryCode, //分类编码
      actionType: "exam_test", //业务类型 答题/练习【填写exam_test】
      userAnswer: item.userAnswer, //答案，选项题答案格式为"A,D"
      actionCode: searchParams.get("actionCode"), //业务编码
      id: item.id, //题目id
    });
    if (res.errCode !== 0) {
      Toast.show({
        icon: "fail",
        content: res.message,
      });
      return;
    }
    item.showAnswer = true; //答案的显示隐藏
    setTestData([...(testData as Array<IData>)]); //刷新视图
  };

  //文本域change事件
  const change = (val: string, item: IData) => {
    item.userAnswer = val;
    setTestData([...(testData as Array<IData>)]);
  };
  useEffect(() => {
    getData();
  }, []);
  //判断显示那个组件
  const ans = (item: IData) => {
    if (item.questionType == "qa") {
      return <AnswersQa item={item} change={change} />;
    } else if (item.questionType == "fill") {
      return <AnswersQa item={item} change={change} />;
    } else if (item.questionType == "one") {
      return <AnswersSingle item={item} />;
    } else if (item.questionType == "check") {
      return <AnswersSingle item={item} />;
    } else if (item.questionType == "code") {
      return <AnswersCode item={item} change={change} />;
    } else if (item.questionType == "many") {
      return <AnswersMult item={item} />;
    }
  };
  return (
    <div className={styles.container}>
      <Swiper className="qd_swiper" indicator={() => null}>
        {testData?.map((item, index) => (
          <Swiper.Item key={item.id}>
            <div className="qd_swiper_item_inner">
              {/* 顶部数量 */}
              <div className="qd_text_top_area">
                <div className="qd_text_top_left">
                  <CalendarOutline fontSize={12} />
                  <span className="qd_text_top_left_num">{index + 1}</span>
                  <span>/{testData.length}</span>
                </div>
                <div className="qd_text_top_right">
                  <span className="qd_text_top_right_text">收藏</span>
                  <StarOutline fontSize={12} />
                </div>
              </div>
              {/* 内容文本域 */}
              <div className="qd_text_conent_area">
                <div className="qd_text_conent_title">
                  <Tag className="qd_text_conent_title_qa" color="primary">
                    {questionTypeData.current[item.questionType]}
                    {/* 问答 */}
                  </Tag>
                  <span key={item.id} className="qd_text_conent_title_text">
                    {item.title}
                  </span>
                </div>
                {/* 根据对应的内容显示 */}
                {ans(item)}

                <div className="qd_text_conent_btn">
                  <Button
                    color="primary"
                    fill="outline"
                    onClick={() => confirm(item)}
                  >
                    确认
                  </Button>
                </div>
              </div>
              {item.showAnswer ? (
                item.userAnswer === item.answer ? (
                  <div className="qd_correcterror" style={{ color: "green" }}>
                    <CheckCircleOutline />
                    回答正确
                  </div>
                ) : (
                  <div className="qd_correcterror" style={{ color: "red" }}>
                    <CloseCircleOutline />
                    回答错误
                  </div>
                )
              ) : null}

              {/* 答案的显示隐藏 */}
              <div
                className="qd_text_answer_area"
                style={{ display: item.showAnswer ? "block" : "none" }}
              >
                <div className="qd_text_answer_title">参考答案：</div>
                <div className="qd_text_answer_conent">
                  <div
                    dangerouslySetInnerHTML={{
                      __html: item.answer.replace(
                        /\<img/gi,
                        '<img style="width:100% !important;height:auto !important" '
                      ),
                    }}
                    className="qd_text_answer_conent_text"
                  ></div>
                </div>
              </div>
            </div>
          </Swiper.Item>
        ))}
      </Swiper>
      {/* 返回上一页 */}
      <div
        className="qd-back"
        onClick={() => {
          navigate(-1),
            Toast.show({
              icon: "loading",
              content: "数据加载中",
              duration: 300,
            });
        }}
      >
        返回上一页
      </div>
    </div>
  );
}

//封装的问答组件
function AnswersQa({ item, change }: { item: IData; change: Function }) {
  return (
    <>
      <div className="qd_text_conent_answer">
        <TextArea
          placeholder="请输入答案"
          value={item.userAnswer ? item.userAnswer : ""}
          onChange={(val) => {
            change(val, item);
          }}
        />
      </div>
      <div className="qd_text_conent_tips">
        此类型的题目暂不支持打分，按正确记分。
      </div>
    </>
  );
}
//封装的单选组件
function AnswersSingle({ item }: { item: IData }) {
  // 单选列表
  let singList: Array<ISingleItem> = JSON.parse(item.optionContent);
  return (
    <>
      <Space direction="vertical" block>
        <Radio.Group
          onChange={(val) => {
            item.userAnswer = val;
          }}
        >
          {singList?.map((item) => {
            return (
              <Radio block key={item.key} value={item.key}>
                {item.value}
              </Radio>
            );
          })}
        </Radio.Group>
      </Space>

      <div className="qd_text_conent_tips">
        此类型的题目暂不支持打分，按正确记分。
      </div>
    </>
  );
}
//封装的多选组件
function AnswersMult({ item }: { item: IData }) {
  // 多选选列表
  let multList: Array<ISingleItem> = JSON.parse(item.optionContent);
  return (
    <>
      <Checkbox.Group
        onChange={(val) => {
          item.userAnswer = val.join(",");
        }}
      >
        <Space direction="vertical">
          {multList?.map((item) => {
            return (
              <Checkbox key={item.key} value={item.key}>
                {item.value}
              </Checkbox>
            );
          })}
        </Space>
      </Checkbox.Group>
      <div className="qd_text_conent_tips">
        此类型的题目暂不支持打分，按正确记分。
      </div>
    </>
  );
}
//封装的编程组件
function AnswersCode({ item, change }: { item: IData; change: Function }) {
  return (
    <>
      <div dangerouslySetInnerHTML={{ __html: item.content }}></div>
      <div className="qd_text_conent_answer">
        <TextArea
          placeholder="请输入答案"
          value={item.userAnswer ? item.userAnswer : ""}
          onChange={(val) => {
            change(val, item);
          }}
        />
      </div>
      <div className="qd_text_conent_tips">
        此类型的题目暂不支持打分，按正确记分。
      </div>
    </>
  );
}

//数据类型
interface IData {
  id: number;
  title: string;
  content: string;
  categoryCode: string;
  answer: string;
  userAnswer?: any;
  wrongAnswer: number;
  analysis?: any;
  questionType: string;
  optionContent?: any;
  invalid?: any;
  tenantId?: any;
  collcetStatus: boolean;
  sort?: any;
  score?: any;
  oerationTotal: number;
  collcetTotal: number;

  showAnswer?: boolean; //前端自己添加的
}
interface ISingleItem {
  key: string;
  value: string;
  sort: number;
}
